<template>
  <div class="home-page">
    <el-container
      id="wrapper"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <el-header class="home-page-header" style="height: 48px">
        <div class="header-item-container">
          <span class="home-page-header-title">
            <a href="/">国产动漫论坛</a>
          </span>
          <div class="header-link">
            <el-menu
              default-active="/"
              class="header-link-menu"
              mode="horizontal"
              @select="routerLink"
            >
              <el-menu-item :index="!userLogin ? '/login' : '/user'">
                <template slot="title">
                  <i class="el-icon-user"></i>
                  <span v-if="userLogin">{{ user.userName }}</span>
                  <span v-if="!userLogin" class="header-link-menu-loginText"
                    >请登录</span
                  >
                </template>
              </el-menu-item>
              <el-menu-item index="/">
                <template slot="title">
                  <i class="el-icon-s-home"></i>
                  <span>首页</span>
                </template>
              </el-menu-item>
            </el-menu>
          </div>
          <el-dropdown class="header-user" @command="userClick">
            <span class="header-user-icon">
              <span class="el-icon-s-tools"></span>
              <!-- <i class="el-icon-arrow-down"></i> -->
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="resetPass" v-if="userLogin"
                >修改密码</el-dropdown-item
              >
              <el-dropdown-item command="account" v-if="userLogin"
                >账号设置</el-dropdown-item
              >
              <el-dropdown-item command="loginOut" v-if="userLogin"
                >注销登录</el-dropdown-item
              >
              <!--<el-dropdown-item command="userImg" v-if="userLogin"
                >上传头像</el-dropdown-item
              >-->
              <el-dropdown-item command="loginIn" v-if="!userLogin"
                >账号登录</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-header>
      <el-dialog
        title="修改密码"
        :visible.sync="isAccountPageVisible"
        class="dialogPage"
        @close="dialogCloseBtn('dialogForm', 'isAccountPageVisible')"
      >
        <el-form
          :model="dialogForm"
          status-icon
          :rules="rules"
          ref="dialogForm"
          label-width="100px"
        >
          <el-form-item label="旧密码:" prop="password">
            <el-input
              v-model="dialogForm.password"
              placeholder="请输入"
              type="password"
              show-password
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="新密码:" prop="newpassword">
            <el-input
              v-model="dialogForm.newpassword"
              placeholder="请输入"
              type="password"
              show-password
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="确认新密码:" prop="checkpassword">
            <el-input
              v-model="dialogForm.checkpassword"
              placeholder="请输入"
              type="password"
              show-password
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="confirmForm('dialogForm')"
            >确认修改</el-button
          >
        </div>
      </el-dialog>
      <el-dialog
        :visible.sync="userImgShow"
        title="上传头像"
        class="dialogPage"
      >
        <el-upload
          class="avatar-uploader"
          action="http://127.0.0.1:8000/avatar/"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-dialog>
      <!-- 修改账号信息的弹出层 -->
      <el-dialog
        title="账号设置"
        :visible.sync="isAccountVisible"
        class="dialogPage"
        @close="dialogCloseBtn('accountForm', 'isAccountVisible')"
      >
        <el-form
          :model="accountForm"
          status-icon
          :rules="accountFormRules"
          ref="accountForm"
          label-width="100px"
        >
          <el-form-item label="用户名:" prop="userName">
            <el-input
              v-model="accountForm.userName"
              placeholder="请输入用户名"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="accountFormSubmit('accountForm')"
            >确认修改</el-button
          >
        </div>
      </el-dialog>
      <el-main class="home-page-main">
        <router-view
          v-if="pageType === 'common'"
          :close="isClose"
          @load="onLoad"
          @notify="notify"
          @showMessage="showMessage"
          :isEdit="isEdit"
          @homeBtnClick="homeBtnClick"
        ></router-view>
        <!-- 发布帖子 -->
        <div class="post-message" v-if="pageType === 'edit'">
          <header class="post-message-title">发布帖子</header>
          <el-form
            :model="noteForm"
            :rules="noteRules"
            ref="noteForm"
            label-width="100px"
          >
            <el-form-item label="标题" prop="title">
              <el-input
                v-model="noteForm.title"
                placeholder="请输入标题"
              ></el-input>
            </el-form-item>
            <el-form-item label="帖子类别" prop="type">
              <el-select v-model="noteForm.type">
                <el-option
                  v-for="item in noteTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <quill-editor
            v-model="noteData"
            :options="noteDataOpt"
            ref="noteData"
          ></quill-editor>
          <footer class="post-message-footer">
            <el-button @click="noteFormCancelClick">取消</el-button>
            <el-button
              type="primary"
              @click="noteFormSubmit('noteForm')"
              icon="el-icon-s-promotion"
              >发布</el-button
            >
          </footer>
        </div>
      </el-main>
    </el-container>
    <el-button
      class="add_note-btn"
      type="primary"
      @click="postMessage"
      size="mini"
      v-if="pageType === 'common' && isHomePath"
      >发帖</el-button
    >
  </div>
</template>

<script>
/* eslint-disable */
export default {
  name: "home-page",
  data() {
    const validatePass = (rule, value, callback) => {
      if (!value) return callback(new Error("请输入密码"));

      setTimeout(() => {
        if (value.toString().length < 6 || value.toString().length > 16)
          callback(new Error("密码长度为6-16个字符"));

        if (this.dialogForm.checkpassword !== "")
          this.$refs.dialogForm.validateField("checkpassword");

        callback();
      }, 1000);
    };
    const validatePass2 = (rule, value, callback) => {
      if (!value) return callback(new Error("请再次输入密码"));

      setTimeout(() => {
        if (value !== this.dialogForm.newpassword)
          callback(new Error("两次输入的密码不一致"));
        else callback();
      }, 1000);
    };
    return {
      noteTypeList: [],
      // userLogin:true,
      // 是否显示loading
      loading: false,
      // 关闭按钮是否被点击, 用以resize图表等
      isClose: false,
      dialogForm: {
        password: "",
        newpassword: "",
        checkpassword: "",
        nickname: "",
        userName: "",
      },
      rules: {
        password: [
          { required: true, trigger: "blur", message: "请输入旧密码" },
        ],
        newpassword: [
          { required: true, trigger: "blur", validator: validatePass },
        ],
        checkpassword: [
          { required: true, trigger: "blur", validator: validatePass2 },
        ],
      },
      isAccountPageVisible: false,
      pageType: "common",
      noteForm: {
        title: "",
        type: "",
      },
      noteRules: {
        title: [{ required: true, trigger: "blur", message: "请输入标题" }],
        type: [{ required: true, trigger: "blur", message: "请选择帖子类别" }],
      },
      isEdit: false,
      noteDataOpt: {},
      noteData: "",
      accountFormRules: {
        nickname: [
          {
            required: true,
            trigger: "blur",
            message: "请输入博客昵称，这是大家称呼你的方式",
          },
        ],
        userName: [
          { required: true, trigger: "blur", message: "请输入用户名" },
        ],
      },
      accountForm: {
        // nickname: "",
        userName: "",
      },
      isAccountVisible: false,
      user: {
        userName: "",
      },
      userInfo: "",
      userImgShow: false,
      imageUrl: "",
    };
  },
  mounted() {
    this.user.userName = this.userName;
    this.userInfo = JSON.parse(window.sessionStorage.getItem("userInfo"));
  },
  methods: {
    // 获取发帖类型数据
    getTypeTie() {
      this.$axios.get("/article/types/").then((res) => {
        // console.log(res,'帖子类型');
        this.noteTypeList = res.data;
      });
    },
    onLoad(state) {
      this.loading = state;
    },
    homeBtnClick() {
      this.pageType = "common";
    },
    onClose() {
      this.isClose = !this.isClose;
    },
    dialogCloseBtn(name, type) {
      this.clearForm(name, type);
    },
    userClick(type) {
      if (type === "loginOut") this.loginOut();
      else if (type === "resetPass") this.isAccountPageVisible = true;
      else if (type === "loginIn") this.login();
      else if (type === "userImg") this.userImgShow = true;
      else if (type === "account")
        (this.accountForm.userName = this.userName),
          (this.accountForm.nickname = this.nickname),
          (this.isAccountVisible = true);
    },
    loginOut() {
      window.sessionStorage.clear();
      window.location.href = "/login";
    },
    login() {
      this.$router.push({ path: "/login" });
    },
    notify({
      title = "",
      message = "成功",
      type = "",
      showClose = false,
    } = {}) {
      this.$notify({
        title: title,
        message: message,
        type: type,
        showClose: showClose,
      });
    },
    showMessage({
      title = "",
      message = "成功",
      type = "info",
      showClose = false,
      center = false,
    } = {}) {
      this.$message({
        title: title,
        message: message,
        type: type,
        showClose: showClose,
        center: center,
      });
    },
    confirmForm(name) {
      this.$refs[name].validate((valid) => {
        if (valid === false) {
          this.notify({ type: "warning", message: "不合法的提交" });
          return;
        }
        this.isAccountPageVisible = false;
        console.log(this.dialogForm);
        const params = {
          email: this.userInfo.email,
          password: this.dialogForm.password,
          newPassword: this.dialogForm.newpassword,
        };
        this.$axios
          .post(`/user/update/`, params)
          .then((ret) => {
            console.log(ret.data);
            window.sessionStorage.clear();
            window.location.href = "/login";
          })
          .catch((res) => {
            this.$message.error(res.response.data.message);
          });
      });
    },
    noteFormSubmit(name) {
      // const ifShow = Window.sessionStorage.getItem("token") || "";
      // if (ifShow !== "") {
      this.$refs[name].validate((valid) => {
        if (valid === false) {
          this.notify({ type: "warning", message: "不合法的提交" });
          return;
        }
        const params = {
          title: this.noteForm.title,
          user_id: window.sessionStorage.getItem("userID"),
          content: this.noteData,
          classification_id: this.noteForm.type,
        };
        this.$axios
          .post("/article/create/", params)
          .then((res) => {
            console.log(res);
            if (res.status === 200) {
              // this.$router.push({ path: "/home" });
              this.isEdit = !this.isEdit;
              this.noteFormCancelClick();
              this.notify({ type: "success", message: "发帖成功" });
            } else {
              this.notify({ type: "error", message: "发帖失败" });
            }
          })
          .catch((res) => {
            this.$message.error(res.response.data.message);
          });
        // this.$http("get", "addNote", params).then(data => {
        //   if (data === "success") {
        //     this.notify({ type: "success", message: "发帖成功" });
        //     this.noteFormCancelClick();
        //     this.isEdit = !this.isEdit;
        //     this.$router.push({ path: "/home" });
        //   } else if (data === "fail") {
        //     this.notify({ type: "error", message: "发帖失败" });
        //   }
        // });
      });
      // } else {
      //   this.$message.error("请登录");
      // }
    },
    reloadUserInfo(res, to = "/") {
      this.$message({
        message: "恭喜你，修改成功",
        type: "success",
      });
      window.sessionStorage.setItem("userInfo", JSON.stringify(res.data));
      window.sessionStorage.setItem("userName", res.data.name);
      window.sessionStorage.setItem("userType", res.data.u_type);
      window.sessionStorage.setItem("userImg", res.data.avatar);
      window.sessionStorage.setItem("userID", res.data.id);
      window.location.href = to;
    },
    accountFormSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid === false) {
          this.notify({ type: "warning", message: "不合法的提交" });
          return;
        }
        this.isAccountPageVisible = false;
        // const params = {
        //   user_name: this.accountForm.userName,
        //   // nickname: this.accountForm.nickname,
        //   user_id: this.userId,
        // };
        const params = {
          email: JSON.parse(window.sessionStorage.getItem("userInfo")).email,
          password: JSON.parse(window.sessionStorage.getItem("userInfo"))
            .password,
          name: this.accountForm.userName,
        };
        this.$axios
          .post("/user/update/", params)
          .then((res) => {
            console.log(res);
            window.sessionStorage.setItem("userID", res.data.id);
            window.sessionStorage.setItem("userName", res.data.name);
            window.sessionStorage.setItem("userImg", res.data.avatar);
            window.sessionStorage.setItem("userType", res.data.u_type);
            window.sessionStorage.setItem("userInfo", JSON.stringify(res.data));
            console.log(res.data.name);
            window.sessionStorage.setItem("userInfo", JSON.stringify(res.data));
            this.isAccountVisible = false;
            this.$message.success("修改成功");
            window.location.href = "/home";
            // window.localtion.reload()
          })
          .catch((err) => {
            this.$message.error("修改失败");
          });

        // this.$http("get", "editUserInfo", params).then((data) => {
        //   if (data === "success") {
        //     this.$store.state.user.nickname = this.accountForm.nickname;
        //     this.$store.state.user.name = this.accountForm.userName;
        //     this.notify({ type: "success", message: "修改成功" });
        //     this.clearForm(name, "isAccountVisible");
        //   } else if (data === "fail") {
        //     this.notify({ type: "error", message: "修改失败" });
        //   }
        // });
        console.log(JSON.parse(window.sessionStorage.getItem("userInfo")));
      });
    },
    clearForm(name, type) {
      this.$refs[name].resetFields();
      this[type] = false;
    },
    noteFormCancelClick() {
      this.$refs.noteForm.resetFields();
      this.pageType = "common";
    },
    routerLink(path) {
      this.$router.push({ path });
    },
    postMessage() {
      this.pageType = "edit";
      this.getTypeTie();
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log(this.imageUrl);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
  computed: {
    userLogin() {
      return window.sessionStorage.getItem("token") || "" !== "" ? true : false;
    },
    // userId() {
    //   if (this.$store.state.user) return this.$store.state.user.user_id;
    //   else return "";
    // },
    // noteTypeList() {
    //   return JSON.parse(localStorage.getItem("sectionList"));
    // },
    isHomePath() {
      const index = this.$route.path.indexOf("/home/");
      const homeFlag = this.$route.path.indexOf("/home");
      return index >= 0 || homeFlag >= 0;
    },
    userName() {
      return window.sessionStorage.getItem("userName") || "" !== ""
        ? window.sessionStorage.getItem("userName")
        : "请登录";
    },
    nickname() {
      if (this.$store.state.user) return this.$store.state.user.nickname;
      else return "";
    },
  },
};
</script>

<style scoped lang="scss">
.home-page {
  height: 100%;
  .add_note-btn {
    position: fixed;
    left: 50%;
    bottom: 100px;
    z-index: 1000;
    margin-left: 510px;
  }
}
.header-link-menu-loginText {
  text-decoration: underline;
  color: red !important;
}
#wrapper {
  padding-top: 50px;
  height: 100%;
  .home-page-main {
    margin: 0 auto;
    padding: 0;
    width: 1000px;
    background: rgba(70, 149, 194, 0.3);
    .post-message {
      margin: 0 auto;
      padding: 0 20px 20px;
      width: 800px;
      background: #fff;
      .post-message-title {
        padding-top: 20px;
        padding-bottom: 20px;
        margin-bottom: 20px;
        font-weight: bold;
        border-bottom: 1px solid #ececec;
      }
      .post-message-footer {
        margin-top: 20px;
      }
    }
  }
  .home-page-header {
    line-height: 48px;
    color: #666;
    background: radial-gradient(#fff, #ccc);
    .header-item-container {
      display: flex;
      margin: 0 auto;
      width: 1200px;
      height: 48px;
      line-height: 48px;
    }
  }
}
</style>

<style lang="scss">
.home-page-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  display: flex;
  background: transparent;
  box-shadow: 0 2px 5px rgba(84, 92, 100, 0.5);
  z-index: 10;
  .header-user {
    height: 100%;
    text-align: right;
    .header-user-icon {
      height: 100%;
      cursor: pointer;
      i {
        color: #666;
      }
    }
  }
  .header-link {
    padding-right: 12px;
    flex: 1;
    text-align: right;
    .header-link-menu {
      height: 48px;
      line-height: 48px;
      border: 0;
      background-color: transparent !important;
      .el-menu-item {
        float: right;
        height: 48px;
        line-height: 48px;
        i {
          color: inherit;
        }
      }
      .is-active {
        border: 0;
        color: #fa7d3c;
      }
      .el-menu-item:not(.is-disabled):hover {
        background-color: transparent;
        color: #fa7d3c;
      }
      .el-menu-item:not(.is-disabled):focus {
        background-color: transparent;
      }
    }
  }
}
.dialogPage {
  .el-dialog {
    border-radius: 8px;
    .el-dialog__header {
      background-color: #ccc;
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
    }
  }
}
.post-message {
  .ql-container {
    min-height: 400px;
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
// .btn-prev {
//   background-color: none;
// }
// .btn-next{
//   background-color: none;
// }
</style>

